function addcookie(name,value,expireHours){
    var cookieString=name+"="+escape(value)+"; path=/";
    //判断是否设置过期时间
    if(expireHours>0){
        var date=new Date();
        date.setTime(date.getTime+expireHours*3600*1000);
        cookieString=cookieString+"; expire="+date.toGMTString();
    }
    getCookieValue("token")=cookieString;
}

function getcookie(name){
    var strcookie=getCookieValue("token");
    var arrcookie=strcookie.split("; ");
    for(var i=0;i<arrcookie.length;i++){
        var arr=arrcookie[i].split("=");
        if(arr[0]==name)return decodeURIComponent(arr[1]); //增加对特殊字符的解析
    }
    return "";
}

function delCookie(name) {//删除cookie
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getcookie(name);
    if (cval != null) getCookieValue("token") = name + "=" + cval + "; path=/;expires=" + exp.toGMTString();
}
function GetQueryString(name) {
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)return  unescape(r[2]); return null;
}
$(function () {
    var wxid=getcookie('wxid');
    var fromurl;
    if (wxid==''){
        var access_code=GetQueryString('code');
        if (access_code==null){
            fromurl=location.href;
            var url='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0b105b7b2755a473&redirect_uri='+encodeURIComponent(fromurl)+'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
            location.href=url;
        }else{
            $.ajax({
                type:'get',
                url:'index.php?c=login&a=getOpenidByCode',
                async:false,
                cache:false,
                data:{code:access_code},
                dataType:'json',
                success:function(result){
                    debugger;
                    if (result!=null && result.hasOwnProperty('openid') && result.openid!=""){
                        addcookie('wxid',result.openid,86400);
                        // alert(result.openid);
                        //getlogininfo(result.openid);
                    }
                    else
                    {
                        alert('微信身份识别失败 \n '+result);
                        //location.href=fromurl;
                    }
                }
            });
        }
    }
});